<template>
  <div class="pine-chart" ref="pineChartRef"></div>
</template>
<script setup>
import { ref, onMounted, inject, watch, nextTick, onUnmounted } from 'vue';

const props = defineProps({
  data: {
    type: Array,
    default: () => [],
  },
  colors: {
    type: Array,
    default: () => [],
  },
});

const pineChartRef = ref(null);
const Echarts = inject('$echarts');

const initEchartsOneFn = () => {
  if (!pineChartRef.value || !Echarts) {
    console.warn('图表容器或 Echarts 实例未准备好');
    return;
  }

  const myChart = Echarts.init(pineChartRef.value);

  let formatNumber = function (num) {
    let reg = /(?=(\B)(\d{3})+$)/g;
    return num.toString().replace(reg, ',');
  };

  const option = {
    backgroundColor: '#fff',
    color: props.colors,
    series: [
      {
        type: 'pie',
        radius: ['15%', '90%'],
        center: ['50%', '50%'],
        data: props.data,
        hoverAnimation: false,
        labelLine: {
          show: false,
          normal: {
            length: 20,
            length2: 120,
            lineStyle: {
              color: '#e6e6e6',
            },
          },
        },
        label: {
          show: true,
          normal: {
            position: 'inside',
            formatter: (params) => {
              const displayName =
                params.name.length > 5
                  ? `${params.name.slice(0, 5)}...`
                  : params.name;

              return `{icon|●}{name|${displayName}}\n{value|${formatNumber(
                params.value + "%"
              )}}`;
            },

            rich: {
              icon: {
                fontSize: 0,
                color: 'inherit',
              },
              name: {
                fontSize: 14,
                padding: [0, 0, 0, 10],
                color: '#555',
              },
              value: {
                fontSize: 14,
                lineHeight: 24,
                fontWeight: 'bolder',
                padding: [10, 0, 0, 20],
                color: '#555',
              },
            },
          },
        },
      },
    ],
  };

  myChart.setOption(option);

  // 清理之前的 resize 监听器
  const resizeHandler = () => {
    myChart.resize();
  };

  window.addEventListener('resize', resizeHandler);

  // 返回清理函数
  return () => {
    window.removeEventListener('resize', resizeHandler);
    myChart.dispose();
  };
};

let chartCleanup = null;

watch(
  () => props.data,
  (newData) => {
    // 清理之前的图表实例
    if (chartCleanup) {
      chartCleanup();
    }

    if (newData && newData.length > 0) {
      nextTick(() => {
        chartCleanup = initEchartsOneFn();
      });
    }
  },
  {
    immediate: true,
    deep: true,
  }
);

onMounted(() => {
  // initEchartsOneFn();
});

onUnmounted(() => {
  // 清理图表实例
  if (chartCleanup) {
    chartCleanup();
  }
});
</script>

<style scoped lang="scss">
.pine-chart {
  width: 300px;
  height: 300px;
}
</style>
